<template>
  <div class="setmeal-add-edit">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ isEdit ? '编辑套餐' : '新增套餐' }}</span>
        <el-button style="float: right; padding: 3px 0" type="text" @click="goBack">返回</el-button>
      </div>
      
      <el-form :model="setmealForm" :rules="rules" ref="setmealForm" label-width="100px" v-loading="loading">
        <el-form-item label="套餐名称" prop="name">
          <el-input v-model="setmealForm.name" placeholder="请输入套餐名称"></el-input>
        </el-form-item>
        
        <el-form-item label="套餐分类" prop="categoryId">
          <el-select v-model="setmealForm.categoryId" placeholder="请选择套餐分类" style="width: 100%">
            <el-option
              v-for="item in categoryOptions"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="套餐价格" prop="price">
          <el-input-number v-model="setmealForm.price" :precision="2" :step="0.1" :min="0" style="width: 100%"></el-input-number>
        </el-form-item>
        
        <el-form-item label="套餐图片" prop="image">
          <el-upload
            class="avatar-uploader"
            action="/api/admin/common/upload"
            :show-file-list="false"
            :headers="uploadHeaders"
            :on-success="handleImageSuccess"
            :before-upload="beforeImageUpload">
            <img v-if="setmealForm.image" :src="setmealForm.image" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        
        <el-form-item label="套餐描述" prop="description">
          <el-input type="textarea" v-model="setmealForm.description" :rows="3" placeholder="请输入套餐描述"></el-input>
        </el-form-item>
        
        <el-form-item label="售卖状态">
          <el-radio-group v-model="setmealForm.status">
            <el-radio :label="1">起售</el-radio>
            <el-radio :label="0">停售</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="包含菜品">
          <div class="dish-list">
            <div class="dish-add">
              <el-button type="primary" @click="showDishSelectDialog">添加菜品</el-button>
            </div>
            <el-table
              v-if="setmealForm.setmealDishes && setmealForm.setmealDishes.length > 0"
              :data="setmealForm.setmealDishes"
              border
              style="width: 100%; margin-top: 10px;">
              <el-table-column
                prop="name"
                label="菜品名称"
                width="180">
              </el-table-column>
              <el-table-column
                prop="price"
                label="单价"
                width="120">
                <template slot-scope="scope">
                  ¥{{ scope.row.price.toFixed(2) }}
                </template>
              </el-table-column>
              <el-table-column
                prop="copies"
                label="份数"
                width="120">
                <template slot-scope="scope">
                  <el-input-number 
                    v-model="scope.row.copies" 
                    :min="1" 
                    :max="99"
                    size="small">
                  </el-input-number>
                </template>
              </el-table-column>
              <el-table-column
                label="操作"
                width="100">
                <template slot-scope="scope">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="removeDish(scope.$index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
            <div v-else class="no-data">暂无菜品，请点击上方按钮添加</div>
          </div>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="submitForm">保存</el-button>
          <el-button @click="goBack">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 菜品选择对话框 -->
    <el-dialog
      title="选择菜品"
      :visible.sync="dishDialogVisible"
      width="800px">
      <div class="dish-filter">
        <el-form :inline="true" :model="dishFilterForm">
          <el-form-item label="菜品名称">
            <el-input v-model="dishFilterForm.name" placeholder="请输入菜品名称" clearable></el-input>
          </el-form-item>
          <el-form-item label="菜品分类">
            <el-select v-model="dishFilterForm.categoryId" placeholder="请选择" clearable>
              <el-option
                v-for="item in dishCategoryOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleDishSearch">查询</el-button>
            <el-button @click="resetDishForm">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      
      <el-table
        ref="dishTable"
        :data="dishList"
        border
        style="width: 100%"
        v-loading="dishLoading"
        @selection-change="handleDishSelectionChange">
        <el-table-column
          type="selection"
          width="55">
        </el-table-column>
        <el-table-column
          prop="name"
          label="菜品名称"
          width="180">
        </el-table-column>
        <el-table-column
          prop="image"
          label="图片"
          width="120">
          <template slot-scope="scope">
            <el-image 
              style="width: 60px; height: 60px"
              :src="scope.row.image" 
              fit="cover"
              :preview-src-list="[scope.row.image]">
            </el-image>
          </template>
        </el-table-column>
        <el-table-column
          prop="categoryName"
          label="分类"
          width="120">
        </el-table-column>
        <el-table-column
          prop="price"
          label="价格"
          width="120">
          <template slot-scope="scope">
            ¥{{ scope.row.price.toFixed(2) }}
          </template>
        </el-table-column>
      </el-table>
      
      <div class="dialog-pagination">
        <el-pagination
          @size-change="handleDishSizeChange"
          @current-change="handleDishCurrentChange"
          :current-page="dishCurrentPage"
          :page-sizes="[5, 10, 20, 30]"
          :page-size="dishPageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="dishTotal">
        </el-pagination>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="dishDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmSelectDishes">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getCategoryList } from '@/api/category'
import { getDishPage } from '@/api/dish'
import { addSetmeal, updateSetmeal, getSetmealById } from '@/api/setmeal'

export default {
  name: 'SetmealAddEdit',
  data() {
    return {
      isEdit: false,
      setmealId: null,
      loading: false,
      categoryOptions: [],
      setmealForm: {
        name: '',
        categoryId: '',
        price: 0,
        image: '',
        description: '',
        status: 1,
        setmealDishes: []
      },
      rules: {
        name: [
          { required: true, message: '请输入套餐名称', trigger: 'blur' },
          { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '请选择套餐分类', trigger: 'change' }
        ],
        price: [
          { required: true, message: '请输入套餐价格', trigger: 'blur' }
        ],
        image: [
          { required: true, message: '请上传套餐图片', trigger: 'change' }
        ]
      },
      // 菜品选择对话框
      dishDialogVisible: false,
      dishLoading: false,
      dishFilterForm: {
        name: '',
        categoryId: ''
      },
      dishCategoryOptions: [],
      dishList: [],
      dishCurrentPage: 1,
      dishPageSize: 10,
      dishTotal: 0,
      selectedDishes: []
    }
  },
  computed: {
    uploadHeaders() {
      return {
        token: localStorage.getItem('token') || ''
      }
    }
  },
  created() {
    // 获取路由参数，判断是新增还是编辑
    this.setmealId = this.$route.params.id
    this.isEdit = !!this.setmealId
    
    // 获取分类列表
    this.fetchCategoryOptions()
    this.fetchDishCategoryOptions()
    
    // 如果是编辑，获取套餐详情
    if (this.isEdit) {
      this.fetchSetmealDetail()
    }
  },
  methods: {
    // 获取套餐分类选项
    fetchCategoryOptions() {
      // 获取套餐分类（type=2）
      getCategoryList(2)
        .then(res => {
          if (res.code === 1) {
            this.categoryOptions = res.data || []
          } else {
            this.$message.error(res.msg || '获取分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取分类列表失败', err)
          this.$message.error('获取分类列表失败')
        })
    },
    
    // 获取菜品分类选项
    fetchDishCategoryOptions() {
      // 获取菜品分类（type=1）
      getCategoryList(1)
        .then(res => {
          if (res.code === 1) {
            this.dishCategoryOptions = res.data || []
          } else {
            this.$message.error(res.msg || '获取菜品分类列表失败')
          }
        })
        .catch(err => {
          console.error('获取菜品分类列表失败', err)
          this.$message.error('获取菜品分类列表失败')
        })
    },
    
    // 获取套餐详情
    fetchSetmealDetail() {
      this.loading = true
      getSetmealById(this.setmealId)
        .then(res => {
          if (res.code === 1) {
            const setmealData = res.data
            // 填充表单数据
            this.setmealForm = {
              id: setmealData.id,
              name: setmealData.name,
              categoryId: setmealData.categoryId,
              price: setmealData.price,
              image: setmealData.image,
              description: setmealData.description || '',
              status: setmealData.status,
              setmealDishes: setmealData.setmealDishes || []
            }
          } else {
            this.$message.error(res.msg || '获取套餐详情失败')
            this.goBack()
          }
        })
        .catch(err => {
          console.error('获取套餐详情失败', err)
          this.$message.error('获取套餐详情失败')
          this.goBack()
        })
        .finally(() => {
          this.loading = false
        })
    },
    
    // 图片上传成功处理
    handleImageSuccess(res, file) {
      console.log('图片上传成功', res, file)
      if (res.code === 1) {
        this.setmealForm.image = res.data
      } else {
        this.$message.error(res.msg || '上传图片失败')
      }
    },
    
    // 图片上传前的验证
    
    beforeImageUpload(file) { // eslint-disable-line no-unused-vars 
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return (isJPG || isPNG) && isLt2M
    },
    
    // 显示菜品选择对话框
    showDishSelectDialog() {
      this.dishDialogVisible = true
      this.fetchDishList()
    },
    
    // 获取菜品列表
    fetchDishList() {
      this.dishLoading = true
      const params = {
        page: this.dishCurrentPage,
        pageSize: this.dishPageSize,
        name: this.dishFilterForm.name,
        categoryId: this.dishFilterForm.categoryId,
        status: 1 // 只查询在售的菜品
      }
      
      getDishPage(params)
        .then(res => {
          if (res.code === 1) {
            this.dishList = res.data.records || []
            this.dishTotal = res.data.total || 0
            
            // 标记已选中的菜品
            this.markSelectedDishes()
          } else {
            this.$message.error(res.msg || '获取菜品列表失败')
          }
        })
        .catch(err => {
          console.error('获取菜品列表失败', err)
          this.$message.error('获取菜品列表失败')
        })
        .finally(() => {
          this.dishLoading = false
        })
    },
    
    // 标记已选中的菜品
    markSelectedDishes() {
      const selectedDishIds = this.setmealForm.setmealDishes.map(item => item.dishId)
      this.$nextTick(() => {
        const table = this.$refs.dishTable
        if (table) {
          this.dishList.forEach(row => {
            if (selectedDishIds.includes(row.id)) {
              table.toggleRowSelection(row, true)
            }
          })
        }
      })
    },
    
    // 菜品查询
    handleDishSearch() {
      this.dishCurrentPage = 1
      this.fetchDishList()
    },
    
    // 重置菜品筛选表单
    resetDishForm() {
      this.dishFilterForm = {
        name: '',
        categoryId: ''
      }
      this.handleDishSearch()
    },
    
    // 菜品多选变更
    handleDishSelectionChange(val) {
      this.selectedDishes = val
    },
    
    // 确认选择菜品
    confirmSelectDishes() {
      if (this.selectedDishes.length === 0) {
        this.$message.warning('请至少选择一个菜品')
        return
      }
      
      // 将选中的菜品添加到套餐中
      const currentDishIds = this.setmealForm.setmealDishes.map(item => item.dishId)
      
      this.selectedDishes.forEach(dish => {
        if (!currentDishIds.includes(dish.id)) {
          this.setmealForm.setmealDishes.push({
            dishId: dish.id,
            name: dish.name,
            price: dish.price,
            copies: 1 // 默认1份
          })
        }
      })
      
      this.dishDialogVisible = false
    },
    
    // 移除菜品
    removeDish(index) {
      this.setmealForm.setmealDishes.splice(index, 1)
    },
    
    // 提交表单
    submitForm() {
      this.$refs.setmealForm.validate(valid => {
        if (valid) {
          // 验证套餐菜品
          if (this.setmealForm.setmealDishes.length === 0) {
            this.$message.warning('请至少添加一个菜品')
            return
          }
          
          this.loading = true
          // 准备提交的数据
          const formData = JSON.parse(JSON.stringify(this.setmealForm))
          
          // 根据isEdit判断是新增还是修改
          const request = this.isEdit ? updateSetmeal(formData) : addSetmeal(formData)
          
          request
            .then(res => {
              if (res.code === 1) {
                this.$message.success(this.isEdit ? '修改成功' : '新增成功')
                this.goBack()
              } else {
                this.$message.error(res.msg || (this.isEdit ? '修改失败' : '新增失败'))
              }
            })
            .catch(err => {
              console.error(this.isEdit ? '修改套餐失败' : '新增套餐失败', err)
              this.$message.error(this.isEdit ? '修改套餐失败' : '新增套餐失败')
            })
            .finally(() => {
              this.loading = false
            })
        } else {
          return false
        }
      })
    },
    
    // 菜品分页相关方法
    handleDishSizeChange(val) {
      this.dishPageSize = val
      this.dishCurrentPage = 1
      this.fetchDishList()
    },
    
    handleDishCurrentChange(val) {
      this.dishCurrentPage = val
      this.fetchDishList()
    },
    
    // 返回列表页
    goBack() {
      this.$router.push('/setmeal')
    }
  }
}
</script>

<style scoped>
.setmeal-add-edit {
  padding: 20px;
}
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.dish-list {
  margin-bottom: 10px;
}
.dish-add {
  margin-bottom: 20px;
}
.no-data {
  color: #909399;
  text-align: center;
  margin: 20px 0;
}
.dish-filter {
  margin-bottom: 20px;
}
.dialog-pagination {
  margin-top: 20px;
  text-align: right;
}
</style>